package expression;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * Created by life3 on 2016/12/31.
 * 数值表达式主要用于获取数值
 *
 */
@ExpressionAn(common = "数值表达式", rank = Integer.MIN_VALUE)
public class ValueExpression implements Expression {
    /**
     * 只允许两个入参
     * 1.属性坐标 String
     * 2.obj Object　ex:data.name
     *
     * $返回对象取值
     * ‘123’ 返回字段串 “123”
     * 123 返回数字 123
     * @return
     */
    public Object exec(Object... objs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String propName = objs[0].toString();
        if(StringUtils.startsWith(propName, "$")) {
            Object obj = objs[1];
            if(null == obj) {
                return null;
            }
            return String.valueOf(BeanUtils.getProperty(obj, propName.substring(1)));
        } else if(StringUtils.startsWith(propName, "'")) {
            return propName.substring(1, propName.length() - 1);
        } else if(StringUtils.equals("", propName)) {
            return "";
        } else {
            return new Integer(propName);
        }
    }
}
